import 'package:flutter/material.dart';
import 'package:flutter1911/bean/category_child_bean_result.dart';
import 'package:flutter1911/bean/category_goods_list_bean_result.dart';
import 'package:flutter1911/bean/category_parent_bean_result.dart';
import 'package:flutter1911/router/application.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../provider/category_provider.dart';
import '../service/service.dart';
import 'package:provider/provider.dart';

class CategoryPage extends StatefulWidget {
  const CategoryPage({Key? key}) : super(key: key);

  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  List<CategoryParentBean?> parentList = [];
  List<CategoryChildBean?> childList = [];
  var listIndex = 0;

  @override
  void initState() {
    _getCategoryChild(1);
    _getCategoryGoodsList(14, 1, 10);
    super.initState();
  }

  //请求一级列表的方法
  Future _getCategoryParent() async {
    await request('getGoodsParent', {'type': 0}, isCategory: true).then(
            (value) =>
        parentList = CategoryParentBeanResult
            .fromJson(value)
            .data!);
    return 'ddd';
  }

  //请求二级列表的方法
  void _getCategoryChild(id) async {
    await request('getGoodsParent', {'type': id}, isCategory: true).then(
            (value) =>
        childList = CategoryChildBeanResult
            .fromJson(value)
            .data!);
    Provider.of<CategoryProvider>(context, listen: false)
        .setChildCategory(childList);
    _getCategoryGoodsList(childList[0]!.id, 1, 10);
  }

  //请求三级列表的方法
  void _getCategoryGoodsList(id, page, size) async {
    await request('categoryGoodsList', '$id/$page/$size').then((value) =>
        Provider.of<CategoryProvider>(context, listen: false)
            .setCategoryGoodsList(
            CategoryGoodsListBeanResult
                .fromJson(value)
                .data!
                .list));
  }

  //一级列表的item
  Widget _leftInkWell(index) {
    bool isClick =
    (index == context
        .watch<CategoryProvider>()
        .parentIndex) ? true : false;
    return InkWell(
      onTap: () {
        _getCategoryChild(parentList[index]!.id);
        Provider.of<CategoryProvider>(context, listen: false)
            .changeParentIndex(index);
        Provider.of<CategoryProvider>(context, listen: false).changeChildIndex(
            0);
      },
      child: Container(
        height: ScreenUtil().setHeight(100),
        padding: const EdgeInsets.only(left: 20, top: 15),
        decoration: BoxDecoration(
            color: isClick ? Colors.black26 : Colors.white,
            border: const Border(
                bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Text(
          parentList[index]!.categoryName!,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }

  //一级分类的列表
  Widget _leftCategoryNav() {
    return Container(
      width: ScreenUtil().setWidth(180),
      decoration: const BoxDecoration(
          border: Border(right: BorderSide(width: 1, color: Colors.black12))),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _leftInkWell(index);
        },
        itemCount: parentList.length,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('分类'),
      ),
      body: Row(
        children: [
          FutureBuilder(
            future: _getCategoryParent(),
            builder: (context, val) {
              if (val.hasData) {
                return _leftCategoryNav();
              } else {
                return const Center(
                  child: Text('加载中...'),
                );
              }
            },
          ),
          Column(
            children: const [
              //右侧上方导航
              RightCategoryNav(),
              //右侧下方商品列表
              Expanded(child: CategoryGoodsList()),
            ],
          )
        ],
      ),
    );
  }
}

class RightCategoryNav extends StatelessWidget {
  const RightCategoryNav({Key? key}) : super(key: key);

  //请求三级列表的方法
  void _getCategoryGoodsList(id, page, size, context) async {
    await request('categoryGoodsList', '$id/$page/$size').then((value) =>
        Provider.of<CategoryProvider>(context, listen: false)
            .setCategoryGoodsList(
            CategoryGoodsListBeanResult
                .fromJson(value)
                .data!
                .list));
  }

  //右侧上方导航的item
  Widget _rightInkWell(CategoryChildBean item, BuildContext context, index) {
    bool isClick =
    (index == context
        .watch<CategoryProvider>()
        .childIndex) ? true : false;
    return InkWell(
      onTap: () {
        Provider.of<CategoryProvider>(context, listen: false).changeChildIndex(
            index);
        _getCategoryGoodsList(item.id, 1, 10, context);
      },
      child: Container(
        color: isClick ? Colors.pink : Colors.white,
        padding: const EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
        child: Text(
          item.categoryName!,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // List list = ['苹果', '联想', '外星人'];
    return Container(
      height: ScreenUtil().setHeight(80),
      width: ScreenUtil().setWidth(570),
      decoration: const BoxDecoration(
          color: Colors.white,
          border:
          Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _rightInkWell(
              context
                  .watch<CategoryProvider>()
                  .childCategoryList[index],
              context,
              index);
        },
        itemCount: context
            .watch<CategoryProvider>()
            .childCategoryList
            .length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }
}

class CategoryGoodsList extends StatelessWidget {
  const CategoryGoodsList({Key? key}) : super(key: key);

  //商品图片
  Widget _goodsImage(index, BuildContext context) {
    return SizedBox(
      width: ScreenUtil().setWidth(200),
      child: Image.network(context
          .watch<CategoryProvider>()
          .categoryGoodsList[index]
          .goodsDefaultIcon!),
    );
  }

  //商品名称
  Widget _goodsName(index, BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(370),
      padding: const EdgeInsets.all(5.0),
      child: Text(
        context
            .watch<CategoryProvider>()
            .categoryGoodsList[index].goodsDesc!,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  //商品价格
  Widget _goodsPrice(index, BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 20.0),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: [
          Text(
            '价格:¥${context
                .watch<CategoryProvider>()
                .categoryGoodsList[index].goodsDefaultPrice}元',
            style: TextStyle(fontSize: ScreenUtil().setSp(20)),
          ),
          Text(
            '原价:¥${context
                .watch<CategoryProvider>()
                .categoryGoodsList[index].goodsDefaultPrice}元',
            style: TextStyle(
                fontSize: ScreenUtil().setSp(20),
                color: Colors.black26,
                decoration: TextDecoration.lineThrough),
          )
        ],
      ),
    );
  }

  //构建商品的Item
  Widget _listWidgetItem(index, BuildContext context) {
    return InkWell(
      onTap: () {
        Application.router!.navigateTo(context, '/detail?id = ${Provider
            .of<CategoryProvider>(context,listen: false)
            .categoryGoodsList[index].id}');
      },
      child: Container(
        padding: const EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: const BoxDecoration(
            color: Colors.white,
            border:
            Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
        child: Row(
          children: [
            _goodsImage(index, context),
            Column(
              children: [
                _goodsName(index, context),
                _goodsPrice(index, context)
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: ScreenUtil().setWidth(570),
      // height: ScreenUtil().setHeight(850),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _listWidgetItem(index, context);
        },
        itemCount: context
            .watch<CategoryProvider>()
            .categoryGoodsList
            .length,
      ),
    );
  }
}
